package com.sangu.dianxiu.fragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.android.volley.VolleyError;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.facebook.drawee.view.SimpleDraweeView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.sangu.dianxiu.ICallBack;
import com.sangu.dianxiu.R;
import com.sangu.dianxiu.adapter.AdvPagerAdapter;
import com.sangu.dianxiu.adapter.RecommendGvAdapter;
import com.sangu.dianxiu.bean.basedata.BannerEntity;
import com.sangu.dianxiu.bean.repairtype.RecommendEntity;
import com.sangu.dianxiu.config.Constants;
import com.sangu.dianxiu.ui.AdvDetailActivity;
import com.sangu.dianxiu.ui.EnterpriseMaintainActivity;
import com.sangu.dianxiu.ui.RecycleActivity;
import com.sangu.dianxiu.ui.RepairActivity;
import com.sangu.dianxiu.ui.LocActivity;
import com.sangu.dianxiu.ui.RepairProjectActivity;
import com.sangu.dianxiu.ui.ShowMasterActivity;
import com.sangu.dianxiu.utils.BaseDataManager;
import com.sangu.dianxiu.utils.RepairTypeManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends Fragment implements BDLocationListener {
    private BaseDataManager baseDataManager=new BaseDataManager();      //使用此类进行基础数据的网络请求
    private RepairTypeManager repairTypeManager=new RepairTypeManager();    //使用此类进行维修类别的网络请求
    private LocationClient locationClient;  //首页也需要定位
    private ArrayList<ImageView> advLists = new ArrayList<>();  //用来保存广告图片
    private ArrayList<BannerEntity.AdImagesEntity> banners=new ArrayList<>();   //广告类
    private ArrayList<ImageView> dots=new ArrayList<>();    //广告上面白点图片
    private AdvPagerAdapter advAdapter;                     //广告的适配器
    private RecommendGvAdapter recommendGvAdapter;          //推荐的适配器
    private ArrayList<RecommendEntity.RecommendsEntity> recommends=new ArrayList<>();   //推荐类

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            vpAdv.setCurrentItem(msg.arg1); //切换广告图片的方法
        }
    };
    @ViewInject(R.id.tv_fragment_home_city)     //使用xutils的注解框架，这样就不用findViewById了
    private TextView tvCurrentCity;
    @ViewInject(R.id.vp_fragment_home_adv)
    private ViewPager vpAdv;
    @ViewInject(R.id.ll_fragment_home_dots)
    private LinearLayout llDots;
    @ViewInject(R.id.iv_fragment_home_repair)
    private ImageView ivRepair;
    @ViewInject(R.id.iv_fragment_home_enterprise_maintain)
    private ImageView ivEnterpriseMaintain;
    @ViewInject(R.id.iv_fragment_home_recycle)
    private ImageView ivRecycle;
    @ViewInject(R.id.gv_fragment_home_recommend)
    private GridView gvRecommend;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_home, container, false);
        ViewUtils.inject(this, view);           //如果没有这一行代码，则上面的注解无效
        initView();                             //进行初始化
        loadAdvData();                          //加载广告数据
        getGridHotData();                       //加载推荐数据
        initLocation();                         //获取首页导航栏的定位城市
        return view;
    }

    private void initView() {
        advAdapter=new AdvPagerAdapter(advLists);
        vpAdv.setAdapter(advAdapter);
        recommendGvAdapter=new RecommendGvAdapter(recommends,getActivity());
        gvRecommend.setAdapter(recommendGvAdapter);
        gvRecommend.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), RepairProjectActivity.class);
                startActivity(intent);
            }
        });
    }

    //接收定位信息，更新首页定位的当前城市
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==Constants.REQUEST_CODE_LOC&&data!=null)
        {
            tvCurrentCity.setText(data.getStringExtra("currentCity"));
        }
    }

    //使用XUtils进行事件监听注解，这样就不必setOnClickListener了
    @OnClick({R.id.iv_fragment_home_cityselect,R.id.tv_fragment_home_map,R.id.iv_fragment_home_repair,
            R.id.iv_fragment_home_enterprise_maintain,R.id.iv_fragment_home_recycle})
    public void onClick(View view)
    {
        Intent intent;
        switch (view.getId())
        {
            case R.id.iv_fragment_home_cityselect:
                intent=new Intent(getActivity(), LocActivity.class);
                startActivityForResult(intent, Constants.REQUEST_CODE_LOC);
                break;
            case R.id.tv_fragment_home_map:
                intent=new Intent(getActivity(), ShowMasterActivity.class);
                startActivity(intent);
                break;
            case R.id.iv_fragment_home_repair:
                intent=new Intent(getActivity(),RepairActivity.class);
                startActivity(intent);
                break;
            case R.id.iv_fragment_home_enterprise_maintain:
                intent=new Intent(getActivity(),EnterpriseMaintainActivity.class);
                startActivity(intent);
                break;
            case R.id.iv_fragment_home_recycle:
                intent=new Intent(getActivity(),RecycleActivity.class);
                startActivity(intent);
                break;
        }
    }
    //加载首页广告数据
    public void loadAdvData()
    {
        HashMap<String,String> map=new HashMap<>();
        baseDataManager.getHomeAdv(map, new ICallBack() {
            @Override
            public void onSuccess(String string) {
                BannerEntity entity = JSONObject.parseObject(string, BannerEntity.class);
                if (entity.getRc() == 0) {
                    banners.addAll(entity.getAdImages());
                    for (int i = 0; i < banners.size(); i++) {
                        SimpleDraweeView iv = new SimpleDraweeView(getActivity());
                        iv.setScaleType(ImageView.ScaleType.FIT_XY);
                        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                        iv.setLayoutParams(layoutParams);
                        iv.setImageURI(Uri.parse(banners.get(i).getImgUrl()));
                        final int finalI = i;
                        iv.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent=new Intent(getActivity(), AdvDetailActivity.class);
                                intent.putExtra("advUrl",banners.get(finalI).getLinkUrl());
                                startActivity(intent);
                            }
                        });
                        advLists.add(iv);
                    }
                    advAdapter.notifyDataSetChanged();
                    //根据广告的数量在广告图片上添加圆点
                    for (int i = 0; i < banners.size(); i++) {
                        ImageView iv = new ImageView(getActivity());
                        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(40, 40);
                        iv.setLayoutParams(params);
                        if (i == 0) {
                            iv.setImageResource(R.mipmap.dotl);
                        } else {
                            iv.setImageResource(R.mipmap.dots);
                        }
                        dots.add(iv);
                        llDots.addView(iv);
                    }
                    //当图片切换的时候切换圆点
                    vpAdv.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                        @Override
                        public void onPageScrolled(int position, float v, int i1) {
                            for (int i = 0; i < dots.size(); i++) {
                                dots.get(i).setImageResource(R.mipmap.dots);
                            }
                            dots.get(position).setImageResource(R.mipmap.dotl);
                        }

                        @Override
                        public void onPageSelected(int i) {
                        }

                        @Override
                        public void onPageScrollStateChanged(int i) {
                        }
                    });
                    //开启一个线程不停地去切换广告图片
                    new Thread() {
                        public void run() {
                            boolean flag = true;
                            int index = -1;
                            while (true) {
                                Message msg = Message.obtain();
                                if (index == advLists.size()) {
                                    index--;
                                    flag = false;
                                } else if (index == 0) {
                                    flag = true;
                                }
                                if (flag) {
                                    index++;
                                } else {
                                    index--;
                                }
                                msg.what = 1;
                                msg.arg1 = index;
                                handler.sendMessage(msg);
                                try {
                                    Thread.sleep(3000);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }.start();
                }
            }
            @Override
            public void onError(VolleyError error) {
            }
        });
    }
    //加载首页推荐数据
    public void getGridHotData() {
        HashMap map=new HashMap();
        repairTypeManager.getRecommendTypeOrProject(map, new ICallBack() {
            @Override
            public void onSuccess(String string) {
                RecommendEntity entity= JSONObject.parseObject(string,RecommendEntity.class);
                if(entity.getRc()==0)
                {
                    recommends.addAll(entity.getRecommends());
                    recommendGvAdapter.notifyDataSetChanged();
                }
            }
            @Override
            public void onError(VolleyError error) {

            }
        });
    }
    private void initLocation()
    {
        locationClient=new LocationClient(getActivity(),getLocOption());
        locationClient.registerLocationListener(this);
        locationClient.start();     //开始定位
    }
    //获得定位的一些参数选项
    private LocationClientOption getLocOption() {
        LocationClientOption option=new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd0911");
        option.setScanSpan(3 * 1000);
        option.setIsNeedAddress(true);
        option.setOpenGps(true);
        return option;
    }
    //当接收到定位信息的时候
    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        String city = bdLocation.getCity();
        if(city!=null)
        {
            tvCurrentCity.setText(city);
            locationClient.stop();  //定位成功后停止定位
        }
        else
        {
            tvCurrentCity.setText("定位失败");
        }
    }

    //在销毁Activity的时候取消volley框架的网络请求，避免消耗多余的流量
    @Override
    public void onDestroy() {
        super.onDestroy();
        baseDataManager.requestQueue.cancelAll(BaseDataManager.class);
        repairTypeManager.requestQueue.cancelAll(RepairTypeManager.class);
    }
}
